/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package es.aurea.presentation.controllers;

import es.aurea.presentation.datas.AccountingDt;
import es.aurea.presentation.datas.AccountingTable;
import es.aurea.presentation.utils.EJBLocator;
import es.aurea.transferobjects.AmountTO;
import es.aurea.transferobjects.GeneralConceptTO;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

/**
 *
 * @author zarius
 */
public class AccountingCtrl {


    private Logger logger = Logger.getLogger(this.getClass().getName());

    private AccountingDt data = new AccountingDt();

    public void init(){
        //Catrga las variables básicas
        if (data.getAccounts()==null){
            List<AccountingTable> tableRow = new ArrayList<AccountingTable>();

            for (GeneralConceptTO row :  EJBLocator.getInstance().getAcountingBean().find()){
                tableRow.add(new AccountingTable(row));
            }

            data.setAccounts(tableRow);
        }
    }

    public AccountingDt getData() {
        logger.warning("AccountingCtrl.getData()");
        init();
        return data;
    }

    public void setData(AccountingDt data) {
        this.data = data;
    }

    public void toggleModal(ActionEvent e) {
        data.setModalRendered(!data.getModalRendered());
    }

    public void commandLinkListener(ActionEvent e) {
        logger.info("commandLinkListener");

        List<AccountingTable> tableRow = new ArrayList<AccountingTable>();

        Integer id = Integer.parseInt(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("selectedId"));

        if (id==null ){
            logger.info("id is null");
            return;
        }else{
            logger.info("id = "+id);
        }

        for (AmountTO row :  EJBLocator.getInstance().getAcountingBean().find(id)){
            tableRow.add(new AccountingTable(row));
        }

        AccountingTable selected = data.getAccountingTable(id);
        if(selected.getShowed()==false){
            logger.info("Adding");
            data.getAccounts().addAll(data.getIndexOfSelected(selected), tableRow);
            data.setShowed(id, true);
        }else{
            logger.info("Removing");
            logger.info(""+data.getAccounts().removeAll(tableRow));
            data.setShowed(id, false);
        }
    }
}
